package com.boot.down.filter;

import com.boot.down.util.CookieUtil;
import com.boot.down.util.JsonUtils;
import com.boot.down.util.generator.StringUtils;
import com.boot.down.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.boot.down.common.Const.EFFECTIVE_TIME;

/**
 * @author dell
 */
@Component
public class SessionResetFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String token = CookieUtil.readCookieInRequest(request);
        if(StringUtils.isNotEmpty(token)){
            //重置session时间
            String userJsonStr = Objects.requireNonNull(redisTemplate.opsForValue().get(token)).toString();
            if(StringUtils.isNotEmpty(userJsonStr)){
                UserVO userVO = JsonUtils.string2Obj(userJsonStr, UserVO.class);
                if(null != userVO){
                    redisTemplate.expire(token, EFFECTIVE_TIME, TimeUnit.SECONDS);
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
